package com.liyunc.demo.bundle.security.filter;

import com.google.common.base.Strings;
import com.liyunc.demo.bundle.security.model.JwtCredential;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author liyuncong
 * @version 1.0
 * @file JwtFilter.java
 * @brief JwtFilter
 * @details JwtFilter
 * @date 2022-03-26
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2022-03-26                liyuncong         Created
 */
@Slf4j
@Component
public class JwtAuthFilter extends AbstractAuthFilter {

    public static final String JWT_FILTER_AUTH = "JwtAuthFilter.AUTH";

    public JwtAuthFilter() {
        super(false);
    }

    @Override
    protected String getAuthFilterName() {
        return this.getClass().getName();
    }

    @Override
    protected Boolean matchesLoginAttempt(HttpServletRequest request) {
        String jwtToken = request.getHeader("authToken");
        request.removeAttribute(JWT_FILTER_AUTH);
        return !Strings.isNullOrEmpty(jwtToken);
    }

    @Override
    protected LoginAttempt matchesAuthCredential(
        HttpServletRequest request, HttpServletResponse response
    ) {
        String jwtToken = request.getHeader("authToken");
        if (Objects.nonNull(jwtToken) && StringUtils.isNotBlank(jwtToken)) {
            request.setAttribute(JWT_FILTER_AUTH, Boolean.TRUE);
        } else {
            request.setAttribute(JWT_FILTER_AUTH, Boolean.FALSE);
        }
        return LoginAttempt.of(Boolean.TRUE, Boolean.FALSE,
            new JwtCredential(jwtToken));
    }
}
